﻿using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;

namespace Web
{
    public class Pagina : Page
    {
        protected string mMensaje;

        public Pagina()
        {
            Load += Pagina_Load;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (Context.Session == null) return;

            //check whether a new session was generated
            if (!Session.IsNewSession) return;

            //check whether a cookies had already been associated with this request
            var sessionCookie = Request.Cookies["ASP.NET_SessionId"];

            if (sessionCookie == null) return;

            var sessionValue = sessionCookie.Value;

            if (!string.IsNullOrEmpty(sessionValue))
            {
                // we have session timeout condition!
                Response.Redirect("SessionTimeout.htm");

                //Session["IsSessionTimeOut"] = true;
            }
        }

        public void LockScreenAfterClick(WebControl wc)
        {
            LockScreenAfterClick(wc, "Procesando...");
        }

        public void LockScreenAfterClick(WebControl wc, string message)
        {
            AddLockScreenScript();

            wc.Attributes.Add("onclick", String.Format("skm_LockScreen('{0}');", message.Replace("'", "\'")));
        }

        public void LockScreenAfterDDLChange(DropDownList ddl)
        {
            LockScreenAfterDDLChange(ddl, "Procesando...");
        }

        public void LockScreenAfterDDLChange(DropDownList ddl, string message)
        {
            // AddLockScreenScript();

            // ddl.Attributes.Add("onchange", String.Format("skm_LockScreen('{0}');", message.Replace("'", "\'")));
        }

        private void AddLockScreenScript()
        {
            if (ClientScript.IsClientScriptIncludeRegistered("skm_LockScreen")) return;

            // Add the JavaScript and <div> elements for freezing the screen

            // Register the JavaScript Include
            ClientScript.RegisterClientScriptInclude("skm_LockScreen",
                                                     Page.ResolveUrl("~/Scripts/LockScreen.js?version=1.0"));

            //Add the <div> elements
            ClientScript.RegisterClientScriptBlock(GetType(), "skm_LockScreen_divs",
                                                   "<div id='skm_LockBackground' class='LockOff'></div><div id='skm_LockPane' class='LockOff'><div id='skm_LockPaneText'>&nbsp;</div></div>",
                                                   false);
        }


        private void LoopButtonOrDropDownList(ControlCollection controlCollection, string message = "Procesando...")
        {
            foreach (Control control in controlCollection)
            {
                if (control is Button)
                    LockScreenAfterClick((WebControl)control, message);
                //else if (control is HyperLink)
                //{
                //    if ()
                //    LockScreenAfterClick((WebControl) control, message);
                    
                //}
                else if (control is DropDownList)
                    LockScreenAfterDDLChange((DropDownList)control, message);

                if (control.Controls.Count > 0)
                    LoopButtonOrDropDownList(control.Controls);
            }
        }

        private void LoopTextBoxes(ControlCollection controlCollection)
        {
            foreach (Control control in controlCollection)
            {
                if (control is TextBox)
                {
                    var tmpTextBox = (TextBox) control;
                    tmpTextBox.Attributes.Add("onfocus", "this.select();");
                }

                if (control.Controls.Count > 0)
                    LoopTextBoxes(control.Controls);
            }
        }

        private void Pagina_Load(object sender, EventArgs e)
        {
            LoopButtonOrDropDownList(Page.Controls);
            LoopTextBoxes(Page.Controls);

            if (IsPostBack) return;

            if (!ObtenerConfiguracion)
            {
                var AppConfig = new Configuracion();

                ServidorReportingServices = AppConfig.ServidorMSSRS;
                CarpetaReportingServices = AppConfig.CarpetaMSSRS;
                ArchivoMaestroSAP = AppConfig.ArchivoMaestroSAP;

                ObtenerConfiguracion = true;
            }

            if (UsuarioID == -99 && GetCurrentPageName() != "login.aspx")
            {
                PopUpMessage("No ha iniciado sesión, al presionar OK será redirigido a la página de Login", "TOYOTA - TIP", "~/login.aspx");
            }
            else
                if (PeriodoActual == null && GetCurrentPageName() != "SeleccionPeriodo.aspx")
                {
                    Response.Redirect("~/forms/SeleccionPeriodo.aspx");
                    //PopUpMessage("Debe seleccionar un período para la sesión, al presionar OK será redirigido a la página de Selección de Período", "TOYOTA - TIP", "~/forms/SeleccionPeriodo.aspx");
                }
        }

        public bool DistribucionAprobada
        {
            get { return ViewState["DistribucionAprobada"] != null && Convert.ToBoolean(ViewState["DistribucionAprobada"]); }
            set { ViewState["DistribucionAprobada"] = value; }
        }

        public bool ObtenerConfiguracion
        {
            get { return Session["ObtenerConfiguracion"] != null && Convert.ToBoolean(Session["ObtenerConfiguracion"]); }
            set { Session["ObtenerConfiguracion"] = value; }
        }

        public string GetCurrentPageName()
        {
            var sPath = HttpContext.Current.Request.Url.AbsolutePath;
            var oInfo = new FileInfo(sPath);
            var sRet = oInfo.Name;
            return sRet;
        }

        protected Periodo PeriodoActual
        {
            get
            {
                if (Session["Periodo"] != null)
                    return (Periodo)Session["Periodo"];

                return null;
            }
            set { Session["Periodo"] = value; }
        }

        protected string DomainName
        {
            get
            {
                return Request.ServerVariables["logon_user"].Split(Convert.ToChar(@"\")).Length == 2 ? Request.ServerVariables["logon_user"].Split(Convert.ToChar(@"\"))[0] : "";
            }
        }

        protected string DomainUser
        {
            get
            {
                return Request.ServerVariables["logon_user"].Split(Convert.ToChar(@"\")).Length == 2 ? Request.ServerVariables["logon_user"].Split(Convert.ToChar(@"\"))[1] : "";
            }
        }

        protected int UsuarioID
        {
            get { return Session["UserId"] == null ? -99 : (int)Session["UserId"]; }
            set { Session["UserId"] = value; }
        }

        protected string NombreUsuario
        {
            get { return Session["NombreUsuario"].ToString(); }
            set { Session["NombreUsuario"] = value; }
        }

        protected int PerfilId
        {
            get { return (int)Session["PerfilId"]; }
            set { Session["PerfilId"] = value; }
        }

        protected void ClearControls()
        {
            ClearControls(this);
        }

        protected static void ClearControls(Control control)
        {
            var textbox = control as TextBox;

            if (textbox != null)
            {
                if (!textbox.Enabled) textbox.Enabled = true;
                textbox.Text = String.Empty;

                if (textbox.TextMode == TextBoxMode.Password)
                    textbox.Attributes.Clear();
            }

            var dropDownList = control as DropDownList;

            if (dropDownList != null)
                if (dropDownList.Items.Count > 0)
                    dropDownList.SelectedIndex = 0;

            foreach (Control childControl in control.Controls)
            {
                ClearControls(childControl);
            }
        }

        public static string Encrypt(string valor)
        {
            if (valor == null) return null;

            try
            {
                byte[] encData_byte = Encoding.UTF8.GetBytes(valor);
                string encodedData = Convert.ToBase64String(encData_byte);

                return encodedData;
            }
            catch (Exception ex)
            {
                throw new Exception("Error Encrypt: " + ex.Message);
            }
        }

        public string Decrypt(string valorEncriptado)
        {
            if (valorEncriptado == null) return null;

            var encoder = new UTF8Encoding();
            Decoder utf8Decode = encoder.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(valorEncriptado);
            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            var decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            var result = new String(decoded_char);
            return result;
        }


        public void PopUpMessage(string message)
        {
            PopUpMessage(message, "Toyota - TIP", null, false);
        }

        public void PopUpMessage(string mensaje, string titulo, string botones, bool persistente)
        {
            if (string.IsNullOrEmpty(mensaje)) return;

            var sbTmp = new StringBuilder();

            sbTmp.Append("$(document).ready(function() { ");
            sbTmp.Append(String.Format("$.prompt(\"{0}\"", Util.Common.Escape(mensaje)));
            sbTmp.Append(", { title: \"" + titulo + "\"");
            sbTmp.Append(", persistent: " + persistente.ToString().ToLower() + "\n");
            sbTmp.Append("}); });");

            ClientScript.RegisterStartupScript(GetType(), "EntersoftScript", sbTmp.ToString(), true);
        }

        public void PopUpMessage(string mensaje, string titulo, string pagina)
        {
            if (string.IsNullOrEmpty(mensaje)) return;

            var sbTmp = new StringBuilder();

            sbTmp.Append("$(document).ready(function() { ");
            sbTmp.Append(String.Format("$.prompt(\"{0}\"", Util.Common.Escape(mensaje)));
            sbTmp.Append(", { title: \"" + titulo + "\"");
            sbTmp.Append(", persistent: true" + "\n");
            sbTmp.Append("ok: function(){ window.location.href = \"" + pagina + "\";}");
            sbTmp.Append("}); ");
            sbTmp.Append("});");

            ClientScript.RegisterStartupScript(GetType(), "EntersoftScript", sbTmp.ToString(), true);
        }

        protected string ArchivoMaestroSAP
        {
            get
            {
                return Session["ArchivoMaestroSAP"] != null ? Session["ArchivoMaestroSAP"].ToString().Replace("[Periodo]", DateTime.ParseExact(PeriodoActual.Llave, "yyyyMMdd", CultureInfo.InvariantCulture).ToString("ddMMyyyy")) : "";
            }
            set
            {
                Session["ArchivoMaestroSAP"] = value;
            }
        }

        public void Redirect(string url, string target, string windowFeatures)
        {
            Redirect(Response, url, target, windowFeatures);
        }

        public static void Redirect(HttpResponse response, string url, string target, string windowFeatures)
        {

            if ((String.IsNullOrEmpty(target) || target.Equals("_self", StringComparison.OrdinalIgnoreCase)) &&
                String.IsNullOrEmpty(windowFeatures))
            {
                response.Redirect(url);
            }
            else
            {
                var page = (Page)HttpContext.Current.Handler;

                if (page == null)
                {
                    throw new InvalidOperationException("Cannot redirect to new window outside Page context.");
                }
                url = page.ResolveClientUrl(url);

                var script = !String.IsNullOrEmpty(windowFeatures) ? @"window.open(""{0}"", ""{1}"", ""{2}"");" : @"window.open(""{0}"", ""{1}"");";
                script = String.Format(script, url, target, windowFeatures);
                page.ClientScript.RegisterStartupScript(typeof(Page), "Redirect", script, true);
            }
        }

        /// <summary>
        ///     Obtener Servidor de Reporting Services  
        /// </summary>
        public string ServidorReportingServices
        {
            get
            {
                return string.IsNullOrEmpty(Session["ServidorReportingServices"].ToString()) ? "" : Session["ServidorReportingServices"].ToString();
            }
            set
            {
                Session["ServidorReportingServices"] = value;
            }
        }

        /// <summary>
        ///     Obtener Carpeta de Reporting Services de la aplicación 
        /// </summary>
        public string CarpetaReportingServices
        {
            get
            {
                return string.IsNullOrEmpty(Session["CarpetaReportingServices"].ToString()) ? "" : Session["CarpetaReportingServices"].ToString();
            }
            set
            {
                Session["CarpetaReportingServices"] = value;
            }
        }
    }
}